package com.tfswx.ruleengine.fn;

import com.greenpineyu.fel.context.FelContext;
import com.tfswx.ruleengine.compute.gzjy.BaseFn;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StrToNum extends BaseFn {

    private static final Pattern CHINESE_NUM = Pattern.compile("[一二三四五六七八九十]+");
    private static final Pattern NUM = Pattern.compile("\\d+");

    @Override
    public Object call(Object[] arguments, FelContext context) {
        String num = (String) arguments[0];
        Matcher matcher = CHINESE_NUM.matcher(num);
        Matcher numMatcher = NUM.matcher(num);
        if (matcher.find()) {
            String chineseNum = matcher.group();
            return zh2arbaNum(chineseNum);
        }
        if (numMatcher.find()) {
            return numMatcher.group();
        }
        return "";
    }

    private int zh2arbaNum(String zhNumStr) {
        Stack<Integer> stack = new Stack<>();
        String numStr = "一二三四五六七八九";
        String unitStr = "十百千万亿";
        String[] ssArr = zhNumStr.split("");
        for (String e : ssArr) {
            int numIndex = numStr.indexOf(e);
            int unitIndex = unitStr.indexOf(e);
            if (numIndex != -1) {
                stack.push(numIndex + 1);
            } else if (unitIndex != -1) {
                int unitNum = (int) Math.pow(10, unitIndex + 1);
                if (stack.isEmpty()) {
                    stack.push(unitNum);
                } else {
                    stack.push(stack.pop() * unitNum);
                }
            }
        }
        return stack.stream().mapToInt(s -> s).sum();
    }

    @Override
    public String getZwmc() {
        return "提取数字中文或者阿拉伯数字";
    }


    @Override
    public List<Param> getParams() {
        List<Param> params = new ArrayList<>();
        params.add(new Param("num"));
        return params;
    }

    @Override
    public String getName() {
        return "strToNum";
    }
}
